// pages/orderComment/orderComment.js
const {
  orderById,
  orderComment,
  orderCommentImageUpload,
  imageBaseUrl
} = require('../../api/url.js')
const app = getApp()
const MAX_IMAGE = 3
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [], //上传的图片信息 [{ src, progress, uploaded }]
    rateContent: '', //评价内容
    isAnonymous: false, //是否匿名评价
    user: {}, //用户信息
    maxImgCount: MAX_IMAGE, //所传图片做大数量
    headImage: "", //订单商品图
    productId: "", //产品id
    descScore: 0, // 描述评价分数
    logiScore: 0, // 物流评价分数
    servScore: 0, // 服务评价分数
    orderId: '' ,//订单id
    genElv:'good',//总体评价 good 好评 medi 中评 bad 差评
  },
  /**
   * @method
   * @desc 设置好评中评差评···················
   */
  setElv(e){
    let that=this
    let elv=e.currentTarget.dataset.elv
    that.setData({
      genElv:elv
    })
  },
  //读取订单详情
  loadOrderDetail(orderId) {
    wx.showLoading({
      title: '加载中',
    })
    var self = this
    const {
      user
    } = this.data
    wx.request({
      url: orderById,
      data: {
        fId: orderId,
        token: wx.getStorageSync("token"),
        loginName: user.loginname,
        fUserId: user.id
      },
      success: function(res) {
        if (res.data.code == 403) {
          wx.hideLoading()
        } else if (res.data.code == 1) {
          wx.hideLoading()
        } else if (res.data.code == 0) {
          wx.hideLoading()
          const order = res.data.response.cont
          if (order && order.list && order.list[0]) {
            if (order.list[0].productImage) {
              self.setData({
                headImage: imageBaseUrl + order.list[0].productImage.fThumbImage
              })
            }
            self.data.productId = order.list.map(i => i.fProductId).join(',')
          }
        }
      }
    })
  },
  //添加评价图片
  tapAddImage() {
    const {
      imgList,
      user
    } = this.data
    const self = this
    wx.chooseImage({
      count: MAX_IMAGE - imgList.length,
      success: (res) => {
        const addImgList = res.tempFilePaths.map(path => ({
          path, //图片路径
          id: '',
          progressText: '0.00', //上传进度
          uploaded: false, //是否上传完成
          uploadTask: null //是否在上传
        }))
        const newImgList = imgList.concat(addImgList) //将选中上传的图片加进上传列表中
        newImgList.forEach((img) => {
          if (!img.uploadTask) { //如果未上传则将其上传
            img.uploadTask = wx.uploadFile({ //上传
              url: orderCommentImageUpload,
              filePath: img.path,
              name: 'file',
              formData: {
                userId: user.userId,
                loginName: user.loginname,
                token: wx.getStorageSync("token"),
              },
              success: (res) => {
                let imgRes
                if (res.data) {
                  try {
                    imgRes = JSON.parse(res.data)
                  } catch (e) {
                  }
                }
                if (imgRes) { //如果存在图片证明图片上传成功，找到上传图片列表中与此此图片相同的图片将其改为已上传完成图片
                  self.setData({
                    imgList: self.data.imgList.map(i => {
                      if (i.path === img.path) {
                        i.id = imgRes[0].fId
                        i.uploaded = true
                      }
                      return i
                    })
                  })
                } else {
                  self.setData({
                    imgList: self.data.imgList.map(i => i.path !== img.path)
                  })
                  wx.showToast({
                    icon: 'none',
                    title: '上传图片失败'
                  })
                }
              }
            })
            img.uploadTask.onProgressUpdate((progressRes) => {
              const {
                progress
              } = progressRes
              self.setData({
                imgList: self.data.imgList.map(i => {
                  if (i.path === img.path) {
                    i.progressText = progress.toFixed(2) //进度
                  }
                  return i
                })
              })
            })
          }
        })
        self.setData({
          imgList: newImgList
        })
      },
      // fail: () => {
      //   wx.hideLoading()
      // }
    })
  },

  checkContent() {
    if (!this.data.rateContent || this.data.rateContent == "") {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none',
        duration: 2000
      })
    }
  },


  submitComment() {
    if (!this.data.rateContent || this.data.rateContent == "") {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    } else if (!this.data.logiScore || !this.data.servScore || !this.data.descScore) {
      wx.showToast({
        title: '店铺评分未完成',
        icon: 'none'
      })
      return
    }
    var self = this
    wx.request({
      url: orderComment,
      data: {
        fUserId: self.data.user.id,
        loginName: self.data.user.loginname,
        token: wx.getStorageSync("token"),
        fDesc: self.data.rateContent,
        fOrderId: self.data.orderId,
        productIds: self.data.productId,
        fPostScore: self.data.logiScore,
        fShopScore: self.data.servScore,
        fProductScore: self.data.descScore,
        fType: 0,
        fIsHide: self.data.isAnonymous ? 1 : 0,
        imageIds: self.data.imgList.filter(i => i.id).map(i => i.id).join(','),
      },
      success: function(res) {
        if (res.data.code == 403) {} else if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        } else if (res.data.code == 0) {
          wx.showToast({
            title: res.data.msg || "评价成功",
            icon: 'none'
          })
          setTimeout(function() {
            wx.navigateBack()
          }, 2000)
        }
      }
    })
  },

  //客户评价时拿到留言内容
  inputRateContent(e) {
    this.data.rateContent = e.detail.value // no need setData
  },
  //设置是否匿名评价
  tapAnonymous() {
    this.setData({
      isAnonymous: !this.data.isAnonymous
    })
  },
  //对订单相关进行评价
  tapScore(e) {
    let {
      score,
      prop
    } = e.currentTarget.dataset
    score = +score
    let scoreText = ''
    if (score === 1) {
      scoreText = '极差'
    } else if (score === 2) {
      scoreText = '失望'
    } else if (score === 3) {
      scoreText = '一般'
    } else if (score === 4) {
      scoreText = '满意'
    } else if (score === 5) {
      scoreText = '完美'
    }
    this.setData({
      [prop + 'Score']: score,
      [prop + 'ScoreText']: scoreText,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      user: app.globalData.userInfo
    })
    // options.id = '8b5a27919f3e4c048da60e21f126a4b9'
    this.setData({
      orderId: options.id
    })
    if (options.id) {
      this.loadOrderDetail(options.id)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})